import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Input, Spin } from 'antd';
import { CloseOutlined, SearchOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);
import chatService from '@/api/services/chatService';
import { useParams } from '@/router/hooks';
import useWindowWidth from '@/hooks/event/use-window-width';

import { removeRefTags } from '@/utils/regexRules';
import { debounce } from 'lodash';

import './styles/history.css';
import NotData from '@/components/NotData';
import { historicalDialogueType, MenuContentType } from '@/common';
import { SvgIcon } from '@/components/icon';
import HistoryLog from '../history-log';

interface HistoryChatProps {
  onChatItemClick?: (chatId: string) => void;
  onChangeChatItem?: (data: historicalDialogueType) => void;
  deleteHistoryDialogue?: (event: any, data: historicalDialogueType) => void;
  setContentType?: (contentType: MenuContentType) => void;
  isSearch?: string | null;
  isDeleteChatHistory?: boolean;
  dataId?: string[];
}

const App: React.FC<HistoryChatProps> = ({
  onChatItemClick,
  onChangeChatItem,
  deleteHistoryDialogue,
  setContentType,
  isSearch = '',
  isDeleteChatHistory,
  dataId = [],
}) => {
  const pageSizeDefault = 50;
  const [chatHistory, setChatHistory] = useState<any[]>([]);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(pageSizeDefault);
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);
  const historyListRef = useRef<HTMLDivElement>(null);
  const dataAppId = localStorage.getItem('appId') || '';
  const { appId } = useParams() as { appId: string };

  const [isInChatPage, setIsInChatPage] = useState<boolean>(false);
  useEffect(() => {
    const isChatPath = location.pathname.includes('/apps/chat');
    setIsInChatPage(isChatPath);
  }, [location.pathname, setIsInChatPage]);

  useEffect(() => {
    appId && debouncedGetHistoryData();
  }, [appId, pageNum, searchQuery, pageSize, isDeleteChatHistory]);

  useEffect(() => {
    if (isSearch != null) {
      setSearchQuery(isSearch);
    } else {
      setSearchQuery('');
    }
  }, [isSearch]);

  const abortControllerRef = useRef<AbortController | null>(null);

  const getHistoryData = async () => {
    setLoading(true);
    try {
      if (appId) {
        const abortController = new AbortController();
        const { signal } = abortController;
        // 如果之前有未完成的请求，取消
        if (abortControllerRef.current) {
          abortControllerRef.current.abort();
        }
        abortControllerRef.current = abortController;

        const today = new Date();
        today.setHours(23, 59, 59, 999);
        const start = new Date();
        start.setHours(0, 0, 0, 0);
        start.setDate(today.getDate() - 7);
        const historyData = await chatService.getHistories(
          {
            appId: dataAppId == appId ? dataAppId : appId,
            pageNum: pageNum,
            pageSize: pageSize,
            dateStart: start.toISOString(),
            dateEnd: today.toISOString(),
            q: searchQuery,
            // isFusionApp: dataId?.length != 0 ? true : false,
            fusionAppId: appId,
            isGlobal: dataId?.length != 0 ? true : false, //所有应用true，反之false
          },
          signal,
        );

        const updatedData = historyData?.data || [];

        if (updatedData.length < pageSize) {
          setHasMore(false);
        }

        const groupedByDate = updatedData.reduce((acc: any, item: any) => {
          const beijingTime = dayjs.utc(item.time).tz('Asia/Shanghai');
          const date = beijingTime.format('YYYY-MM-DD');
          const today = dayjs().tz('Asia/Shanghai').format('YYYY-MM-DD');

          const displayDate = date === today ? '今天' : date;

          if (!acc[date]) {
            acc[date] = { time: displayDate, child: [] };
          }
          acc[date].child.push(item);
          return acc;
        }, {} as { [key: string]: { time: string; child: any[] } });

        const result = Object.keys(groupedByDate).map((key) => groupedByDate[key]);

        if (pageNum === 1) {
          setChatHistory(result);
        } else {
          const mergedHistory = [...chatHistory, ...result].reduce((acc, item) => {
            const existingItem = acc.find((i: any) => i.time === item.time);
            if (existingItem) {
              existingItem.child.push(...item.child);
            } else {
              acc.push(item);
            }
            return acc;
          }, []);

          // 按日期排序
          mergedHistory.sort((a: any, b: any) => {
            const dateA = a.time === '今天' ? dayjs().format('YYYY-MM-DD') : a.time;
            const dateB = b.time === '今天' ? dayjs().format('YYYY-MM-DD') : b.time;
            return dayjs(dateB).diff(dayjs(dateA));
          });

          setChatHistory(mergedHistory);
        }
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const debouncedGetHistoryData = debounce(getHistoryData, 300);

  const onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
    setPageNum(1);
    setPageSize(pageSizeDefault);
    setHasMore(true);
  };

  const handleScroll = useCallback(() => {
    if (historyListRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = historyListRef.current;

      if (scrollHeight - scrollTop <= clientHeight + 100 && !loading && hasMore) {
        setLoading(true);
        setPageSize((prevPageSize) => prevPageSize + pageSizeDefault);
      }
    }
  }, [loading, hasMore]);

  useEffect(() => {
    const container = historyListRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
    }
    return () => {
      if (container) {
        container.removeEventListener('scroll', handleScroll);
      }
    };
  }, [handleScroll]);

  const { isPc } = useWindowWidth();

  const handleChatItemClick = (item: historicalDialogueType) => {
    if (onChangeChatItem) {
      onChangeChatItem(item);
    }
    if (onChatItemClick) {
      onChatItemClick(item._id);
    }
  };

  return (
    <div
      className="w-full"
      style={{
        // backgroundColor: '#EDF0F8',
        backgroundColor: 'transparent',
        borderRadius: 6,
      }}
    >
      <div
        className={`h-full w-full ${
          !isPc && 'overflow-auto [-ms-overflow-style:none] [scrollbar-width:none]'
        }`}
        ref={containerRef}
        style={{
          // height: isPc ? 'calc(100vh - 200px)' : 'calc(100vh - 110px)',
          height: isPc ? 'unset' : 'calc(100vh - 0px)',
        }}
      >
        <div className={` w-full rounded-default px-4 pt-2 `}>
          <div className="flex h-[50px] items-center justify-between ">
            <div className="flex items-center rounded-md text-base font-font-weight-600 text-text-5">
              我的对话
            </div>
            <div
              className="cursor-pointer"
              onClick={() => {
                // setShowkeyHistory(false);
                setContentType && setContentType('homepage');
              }}
            >
              <CloseOutlined className="text-base text-[#86909C]" />
            </div>
          </div>
          <HistoryLog
            chatHistory={chatHistory}
            hasMore={hasMore}
            loading={loading}
            onInputChange={onInputChange}
            handleChatItemClick={handleChatItemClick}
            deleteHistoryDialogue={deleteHistoryDialogue}
          />
        </div>
      </div>
    </div>
  );
};

export default App;
